//
//  LoginPwdViewModel.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/3/30.
//

import Foundation
import Combine

final class LoginPwdViewModel: ObservableObject {
    var description: String = ""

    @Published var txtoken: String? {
            didSet {
                // 当 txtoken 改变时，自动发起网络请求
                oneKeyLogin(token: txtoken)
            }
        }
    @Published var isAgreed = false
    @Published var account: String = "18100175531"
    @Published var password: String = "www52azhi"
    @Published var errorMessage: String = ""
    @Published var isPasswordHidden: Bool = true
    @Published var isRememberPwd: Bool = false
    @Published var showError = false
    @Published var isLoading: Bool = false
    @Published var to: Bool = false
    @Published var showAlert: Bool = false
    @Published var showToast = false
    @Published var alertConfig: AlertConfig?
    var toastMsg = ""
    private let bindAccountSubject = PassthroughSubject<Bool, Never>()
    private let errorRedirectSubject = PassthroughSubject<Int, Never>()
    
    private lazy var  wechatLoginFlow = WeChatLoginFlow()
    private lazy var  appleLoginFlow = AppleLoginFlow(errorRedirectSubject: errorRedirectSubject, bindAccountSubject: bindAccountSubject)
    private lazy var oneKeyLoginFlow = OneKeyLoginFlow()
    var cancellables = Set<AnyCancellable>()
    
    

    private let authManager = AuthManager.shared

    var isInputEmpty: Bool {
        account.isEmpty || password.isEmpty
    }

    var isAccountValid: Bool {
        account.isEmail || account.isPhoneNum
    }

    var isPasswordValid: Bool {
        password.count >= 6
    }

    var isInputValid: Bool {
        isAccountValid && isPasswordValid && !isInputEmpty
    }
    
    deinit{
        print("deinitdeinitdeinitdeinit")
    }
    func login()
    {
        if isAgreed == false {
            print("error: 没有点击同意协议")
            return
        }
        UIApplication.shared.hideKeyboard()
        let loginPwdApi = AuthAPI.LoginPwd(body: .init(userName: account, password: password))
        NetworkManager.shared.send(loginPwdApi) {[weak self] result in
              switch result {
              case .success(let response):
                  AuthManager.shared.saveToken(response.data?.access_token ?? "")
                  print("Login success! Access Token: \(response.data?.access_token ?? "")")
                  // 处理登录成功后的逻辑
              case .failure(let error):
                  if let networkError = error as? NetworkError {
                      switch networkError {
                      case .apiError(let apiError): // 这里再解包 APIError
                          DispatchQueue.main.async(execute: {
                              self?.showToast = true
                              self?.toastMsg = apiError.message
                          })
                      default:
                          print("Other Network Error: \(networkError.localizedDescription)")
                      }
                  } else {
                      print("Unknown error: \(error.localizedDescription)")
                  }
              }
          }
    }
    
    // 微信授权登录
    func wechatLogin()
    {
        wechatLoginFlow.start()
            .sink(receiveCompletion: { [weak self]  completion in
                switch completion {
                case .finished:
                    print("登录流程完成")
                case .failure(let error):
                    if let networkError = error as? NetworkError {
                        switch networkError {
                        case .apiError(let apiError): // 这里再解包 APIError
                            if apiError.code == 10012 {
                                self?.triggerErrorAlert(message: "绑定手机号，可同步已联网设备到该新账号内")
                            }
                        default:
                            print("Other Network Error: \(networkError.localizedDescription)")
                        }
                    } else {
                        print("Unknown error: \(error.localizedDescription)")
                    }
                }
            }, receiveValue: { userInfo in
                print("登录成功，用户信息: \(userInfo)")
                AuthManager.shared.tuyaLogined()
            })
            .store(in: &cancellables)
    }
    
    // 一键登陆
    func oneKeyLogin(token: String?)
    {
        guard let token = token else {
            Logger.log(.error, message: "一键登录授权获取的token为null", tag: .login)
            return
        }
        
        oneKeyLoginFlow.start(txtoken: token)
            .sink(receiveCompletion: {completion in
                switch completion {
                    case .finished:
                        break;
                    case .failure(let error):
                        Logger.log(.debug,message: "一键登录失败: \(error.localizedDescription)", tag: .login)
                    }
            }, receiveValue: { result in
                Logger.log(.debug,message: "一键登录成功", tag: .login)
                AuthManager.shared.tuyaLogined()
            }).store(in: &cancellables)
        
    }
    
    // 苹果授权登录
    func appleLogin() {
        appleLoginFlow.start()
                .receive(on: DispatchQueue.main)
                .sink { completion in
                    if case let .failure(error) = completion {
                        let nsError = error as NSError
                        if nsError.code == 10012 {
                            // 需要绑定
                            
                        }
                        self.errorMessage = nsError.localizedDescription
                    }
                } receiveValue: { result in
                    Logger.log(.debug, message: "apple 授权并登录成功", tag: .login)
                }
                .store(in: &cancellables)
        
        appleLoginFlow.errorRedirectSubject?
            .sink { [weak self] code in
                if (code == 10012){
                    self?.triggerErrorAlert(message: "绑定手机号，可同步已联网设备到该新账号内")
                }
            }
        .store(in: &cancellables)
        
 
    }
    
    func verify() -> Bool {
        if account.isEmpty {
            showError = true
            errorMessage = "Please enter your account."
            return false
        }

        if !account.isEmail || !account.isPhoneNum {
            showError = true
            errorMessage = "Account format is incorrect."
            return false
        }

        if password.isEmpty {
            showError = true
            errorMessage = "Please enter your password."
            return false
        }

        return true
    }
    
    func handleOpenURL(url: URL)
    {
        // 只关心 微信授权回调
        if !url.absoluteURL.absoluteString.contains(WECHAT_UNISAL_LINK)
        {
            return
        }
        wechatLoginFlow.handleOpenURL(url: url)
    }
    
    // 三方登录时，用户选择绑定账号与否
    func bindSelect(isAgree: Bool) {
        bindAccountSubject.send(isAgree)
    }
    
    func triggerErrorAlert(message: String) {
        
        DispatchQueue.main.async {
            self.alertConfig = AlertConfig(
                title: "确认绑定",
                message: message,
                buttons: [
                    AlertButton(title: "取消", titleColor: AppColors.Gy1) {[weak self] in
                        print("取消操作")
                        self?.bindSelect(isAgree: false)
                         self?.showAlert = false
                        
                    },
                    AlertButton(title: "绑定", titleColor: AppColors.Brand6) {[weak self] in
                        print("绑定操作")
                        self?.bindSelect(isAgree: true)
                        self?.showAlert = false
                    }
                ]
            )
            self.showAlert = true
        }
    }
    
    func showAgreeAlert(message: String) {
        
        DispatchQueue.main.async {
            self.alertConfig = AlertConfig(
                title: "",
                message: message,
                buttons: [
                    AlertButton(title: "取消", titleColor: AppColors.Gy1) {[weak self] in
                        print("取消操作")
                        self?.bindSelect(isAgree: false)
                         self?.showAlert = false
                        
                    },
                    AlertButton(title: "绑定", titleColor: AppColors.Brand6) {[weak self] in
                        print("绑定操作")
                        self?.bindSelect(isAgree: true)
                        self?.showAlert = false
                    }
                ]
            )
            self.showAlert = true
        }
    }
}


struct AlertConfig {
    let title: String
    let message: String
    let buttons: [AlertButton]
}

